package 练习增删改操作;

import JDBC工具包.JDBCPackage;
import org.junit.Test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @作者:侯国威
 * @时间: 2020/4/15/11:56
 * @邮箱:1045077189@qq.com
 */
public class Index {

    public static void main(String[] args) {
        Index index = new Index();
        index.func();
    }

    public void func() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入id:");
        int id = scanner.nextInt();

        System.out.println("请输入姓名:");
        String name = scanner.next();

        System.out.println("请输入年龄:");
        int age = scanner.nextInt();


        System.out.println("请输入金钱:");
        String money = scanner.next();

        System.out.println("输入体重");
        String height = scanner.next();

        System.out.println("输入身高:");

        String weight = scanner.next();
        //这里只需要填写sql语句
        String sql = "insert into star(id, name, money, age, weight, height) VALUES (?,?,?,?,?,?)";

        int insertcount = update(sql, id, name, age, money, height, weight);

        if (insertcount > 0) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }


    }

    public int update(String sql, Object... args) {
        Connection connection = null;

        PreparedStatement preparedStatement = null;

        try {
            connection = JDBCPackage.getconnection();

            preparedStatement = connection.prepareStatement(sql);

            //填充占位符
            for (int i = 0; i < args.length; i++) {

                preparedStatement.setObject(i + 1, args[i]);//参数声明错误
            }

            //方式二
            return preparedStatement.executeUpdate();
            //执行方式一
//            return preparedStatement.execute(); 在增删改时，没返回结果

        } catch (IOException | ClassNotFoundException | SQLException e) {

            e.printStackTrace();

        } finally {

            JDBCPackage.closeResource(connection, preparedStatement);

        }
        return 0;
    }
}
